package com.bjwl.display.service.safty.impl;

import com.bjwl.display.mapper.safty.SysMenuMapper;
import com.bjwl.display.model.SysMenu;
import com.bjwl.display.service.safty.SysMenuService;
import com.bjwl.display.vo.SysMenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements SysMenuService{

    @Autowired
    private SysMenuMapper sysMenuMapper;
    /**
     * 获取所有菜单，并以树形结构显示
     * @return
     */
    @Override
    public List<SysMenuVO> metuTree() {
//        获取到所有菜单信息
        List<SysMenu> sysMenus = sysMenuMapper.queryMenuList();
        List<SysMenuVO> sysMenuVOList = sysMenus.stream().filter(sysMenu -> sysMenu.getParent_id() == 0 && sysMenu.getPerms() == 2)
                .map(sysMenu -> {
                    SysMenuVO sysMenuVO = new SysMenuVO();
                    sysMenuVO.setMenu_id(sysMenu.getMenu_id());
                    sysMenuVO.setName(sysMenu.getName());
                    sysMenuVO.setIcon(sysMenu.getIcon());
                    sysMenuVO.setUrl(sysMenu.getUrl());
                    sysMenuVO.setOrder_num(sysMenu.getOrder_num());
                    sysMenuVO.setParent_id(sysMenu.getParent_id());
                    sysMenuVO.setPerms(sysMenu.getPerms());
                    sysMenuVO.setType(sysMenu.getType());
                    sysMenuVO.setChildSysMenu(getChildernMenuList(sysMenu,sysMenus));
                    return sysMenuVO;
                })
                .collect(Collectors.toList());
        return sysMenuVOList;
    }

    /**
     * 递归获取子菜单
     * @param root
     * @param all
     * @return
     */
    private List<SysMenuVO> getChildernMenuList(SysMenu root,List<SysMenu> all){
        List<SysMenuVO> list = all.stream().filter(sysMenu -> {
            return sysMenu.getParent_id() == root.getMenu_id();
        })
                .map(menu->{
                    SysMenuVO sysMenuVO = new SysMenuVO();
                    sysMenuVO.setMenu_id(menu.getMenu_id());
                    sysMenuVO.setName(menu.getName());
                    sysMenuVO.setIcon(menu.getIcon());
                    sysMenuVO.setUrl(menu.getUrl());
                    sysMenuVO.setOrder_num(menu.getOrder_num());
                    sysMenuVO.setParent_id(menu.getParent_id());
                    sysMenuVO.setPerms(menu.getPerms());
                    sysMenuVO.setType(menu.getType());
                    sysMenuVO.setChildSysMenu(getChildernMenuList(menu,all));
                    return sysMenuVO;
                })
                .collect(Collectors.toList());
        return list;
    }
}
